var TIM = require('../../../../utils/tim-wx.js');
var COS = require('../../../../utils/cos-wx-sdk-v5.js');
const app = getApp();
// pages/kefu/kefu.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    selToID: '',
    friendId: '',
    friendName: '',
    friendAvatarUrl: '',
    content: '',
    selSess: '',
    list: [], //type 0 自己  1他人 
    scrollTop: 0, //控制上滑距离
    windowHeight: 0, //页面高度
    type: false,
    length: '',
    bqtype: true,
    imgtype: true,
    id: "",
    bqlist: [{
      img: '../../images/emoji/zy.png',
      text: '[龇牙]'
    },
    {
      img: '../../images/emoji/tp.png',
      text: '[调皮]'
    },
    {
      img: '../../images/emoji/lh.png',
      text: '[流汗]'
    },
    {
      img: '../../images/emoji/tx.png',
      text: '[偷笑]'
    },
    {
      img: '../../images/emoji/zj2.png',
      text: '[再见]'
    },
    {
      img: '../../images/emoji/qd.png',
      text: '[敲打]'
    },
    {
      img: '../../images/emoji/ch.png',
      text: '[擦汗]'
    },
    {
      img: '../../images/emoji/zt.png',
      text: '[猪头]'
    },
    {
      img: '../../images/emoji/mg.png',
      text: '[玫瑰]'
    },
    {
      img: '../../images/emoji/ll.png',
      text: '[流泪]'
    },
    {
      img: '../../images/emoji/dk.png',
      text: '[大哭]'
    },
    {
      img: '../../images/emoji/x.png',
      text: '[嘘]'
    },
    {
      img: '../../images/emoji/k.png',
      text: '[酷]'
    },
    {
      img: '../../images/emoji/zk.png',
      text: '[抓狂]'
    },
    {
      img: '../../images/emoji/wq.png',
      text: '[委屈]'
    },
    {
      img: '../../images/emoji/bb.png',
      text: '[抱抱]'
    },
    {
      img: '../../images/emoji/zd.png',
      text: '[炸弹]'
    },
    {
      img: '../../images/emoji/cd1.png',
      text: '[菜刀]'
    },
    {
      img: '../../images/emoji/ka.png',
      text: '[可爱]'
    },
    {
      img: '../../images/emoji/s1.png',
      text: '[色]'
    },
    {
      img: '../../images/emoji/hx.png',
      text: '[害羞]'
    },
    {
      img: '../../images/emoji/dy.png',
      text: '[得意]'
    },
    {
      img: '../../images/emoji/t.png',
      text: '[吐]'
    },
    {
      img: '../../images/emoji/wx.png',
      text: '[微笑]'
    },
    {
      img: '../../images/emoji/n.png',
      text: '[怒]'
    },
    {
      img: '../../images/emoji/gg.png',
      text: '[尴尬]'
    },
    {
      img: '../../images/emoji/jk.png',
      text: '[惊恐]'
    },
    {
      img: '../../images/emoji/lh1.png',
      text: '[冷汗]'
    },
    {
      img: '../../images/emoji/ax.png',
      text: '[爱心]'
    },
    {
      img: '../../images/emoji/sa.png',
      text: '[示爱]'
    },
    {
      img: '../../images/emoji/by.png',
      text: '[白眼]'
    },
    {
      img: '../../images/emoji/am.png',
      text: '[傲慢]'
    },
    {
      img: '../../images/emoji/ng.png',
      text: '[难过]'
    },
    {
      img: '../../images/emoji/jy.png',
      text: '[惊讶]'
    },
    {
      img: '../../images/emoji/yw.png',
      text: '[疑问]'
    },
    {
      img: '../../images/emoji/k1.png',
      text: '[困]'
    },
    {
      img: '../../images/emoji/mmd.png',
      text: '[么么哒]'
    },
    {
      img: '../../images/emoji/hx1.png',
      text: '[憨笑]'
    },
    {
      img: '../../images/emoji/aq.png',
      text: '[爱情]'
    },
    {
      img: '../../images/emoji/s.png',
      text: '[衰]'
    },
    {
      img: '../../images/emoji/pz.png',
      text: '[撇嘴]'
    },
    {
      img: '../../images/emoji/yx.png',
      text: '[阴险]'
    },
    {
      img: '../../images/emoji/fd2.png',
      text: '[奋斗]'
    },
    {
      img: '../../images/emoji/fd.png',
      text: '[发呆]'
    },
    {
      img: '../../images/emoji/yhh.png',
      text: '[右哼哼]'
    },
    {
      img: '../../images/emoji/bb.png',
      text: '[抱抱]'
    },
    {
      img: '../../images/emoji/hx2.png',
      text: '[坏笑]'
    },
    {
      img: '../../images/emoji/fw.png',
      text: '[飞吻]'
    },
    {
      img: '../../images/emoji/bs.png',
      text: '[鄙视]'
    },
    {
      img: '../../images/emoji/y.png',
      text: '[晕]'
    },
    {
      img: '../../images/emoji/db.png',
      text: '[大兵]'
    },
    {
      img: '../../images/emoji/kl.png',
      text: '[可怜]'
    },
    {
      img: '../../images/emoji/q.png',
      text: '[强]'
    },
    {
      img: '../../images/emoji/r.png',
      text: '[弱]'
    },
    {
      img: '../../images/emoji/ws.png',
      text: '[握手]'
    },
    {
      img: '../../images/emoji/sl.png',
      text: '[胜利]'
    },
    {
      img: '../../images/emoji/bq.png',
      text: '[抱拳]'
    },
    {
      img: '../../images/emoji/dl.png',
      text: '[凋谢]'
    },
    {
      img: '../../images/emoji/mf.png',
      text: '[米饭]'
    },
    {
      img: '../../images/emoji/dg.png',
      text: '[蛋糕]'
    },
    {
      img: '../../images/emoji/xg.png',
      text: '[西瓜]'
    },
    {
      img: '../../images/emoji/pj.png',
      text: '[啤酒]'
    },
    {
      img: '../../images/emoji/pc.png',
      text: '[瓢虫]'
    },
    {
      img: '../../images/emoji/gy.png',
      text: '[勾引]'
    },
    {
      img: '../../images/emoji/[OK]@2x.png',
      text: '[OK]'
    },
    {
      img: '../../images/emoji/an.png',
      text: '[爱你]'
    },
    {
      img: '../../images/emoji/kf.png',
      text: '[咖啡]'
    },
    {
      img: '../../images/emoji/yl.png',
      text: '[月亮]'
    },
    {
      img: '../../images/emoji/d.png',
      text: '[刀]'
    },
    {
      img: '../../images/emoji/fd1.png',
      text: '[发抖]'
    },
    {
      img: '../../images/emoji/cj.png',
      text: '[差劲]'
    },
    {
      img: '../../images/emoji/qt.png',
      text: '[拳头]'
    },
    {
      img: '../../images/emoji/xsl.png',
      text: '[心碎了]'
    },
    {
      img: '../../images/emoji/ty.png',
      text: '[太阳]'
    },
    {
      img: '../../images/emoji/lw.png',
      text: '[礼物]'
    },
    {
      img: '../../images/emoji/pq.png',
      text: '[皮球]'
    },
    {
      img: '../../images/emoji/kl1.png',
      text: '[骷髅]'
    },
    {
      img: '../../images/emoji/hs.png',
      text: '[挥手]'
    },
    {
      img: '../../images/emoji/sd.png',
      text: '[闪电]'
    },
    {
      img: '../../images/emoji/je.png',
      text: '[饥饿]'
    },
    {
      img: '../../images/emoji/zm.png',
      text: '[咒骂]'
    },
    {
      img: '../../images/emoji/zm1.png',
      text: '[折磨]'
    },
    {
      img: '../../images/emoji/kb.png',
      text: '[抠鼻]'
    },
    {
      img: '../../images/emoji/gz.png',
      text: '[鼓掌]'
    },
    {
      img: '../../images/emoji/qdl.png',
      text: '[糗大了]'
    },
    {
      img: '../../images/emoji/zhh.png',
      text: '[左哼哼]'
    },
    {
      img: '../../images/emoji/dhq.png',
      text: '[打哈欠]'
    },
    {
      img: '../../images/emoji/kkl.png',
      text: '[快哭了]'
    },
    {
      img: '../../images/emoji/x1.png',
      text: '[吓]'
    },
    {
      img: '../../images/emoji/lq.png',
      text: '[篮球]'
    },
    {
      img: '../../images/emoji/pp.png',
      text: '[乒乓]'
    },
    {
      img: '../../images/emoji/[NO]@2x.png',
      text: '[NO]'
    },
    {
      img: '../../images/emoji/tt.png',
      text: '[跳跳]'
    },
    {
      img: '../../images/emoji/oh.png',
      text: '[怄火]'
    },
    {
      img: '../../images/emoji/zq.png',
      text: '[转圈]'
    },
    {
      img: '../../images/emoji/kt.png',
      text: '[磕头]'
    },
    {
      img: '../../images/emoji/ht.png',
      text: '[回头]'
    },
    {
      img: '../../images/emoji/ts.png',
      text: '[跳绳]'
    },
    {
      img: '../../images/emoji/jd.png',
      text: '[激动]'
    },
    {
      img: '../../images/emoji/jw.png',
      text: '[街舞]'
    },
    {
      img: '../../images/emoji/xw.png',
      text: '[献吻]'
    },
    {
      img: '../../images/emoji/ztj.png',
      text: '[左太极]'
    },
    {
      img: '../../images/emoji/ytj.png',
      text: '[右太极]'
    },
    {
      img: '../../images/emoji/bz.png',
      text: '[闭嘴]'
    },
    {
      img: '../../images/emoji/mm.png',
      text: '[猫咪]'
    },
    {
      img: '../../images/emoji/hsx.png',
      text: '[红双喜]'
    },
    {
      img: '../../images/emoji/bp.png',
      text: '[鞭炮]'
    },
    {
      img: '../../images/emoji/hdl.png',
      text: '[红灯笼]'
    },
    {
      img: '../../images/emoji/mj.png',
      text: '[麻将]'
    },
    {
      img: '../../images/emoji/mkf.png',
      text: '[麦克风]'
    },
    {
      img: '../../images/emoji/lpd.png',
      text: '[礼物袋]'
    },
    {
      img: '../../images/emoji/xf.png',
      text: '[信封]'
    },
    {
      img: '../../images/emoji/xq.png',
      text: '[象棋]'
    },
    {
      img: '../../images/emoji/cd.png',
      text: '[彩带]'
    },
    {
      img: '../../images/emoji/lz.png',
      text: '[蜡烛]'
    },
    {
      img: '../../images/emoji/bj.png',
      text: '[爆筋]'
    },
    {
      img: '../../images/emoji/bbt.png',
      text: '[棒棒糖]'
    },
    {
      img: '../../images/emoji/np.png',
      text: '[奶瓶]'
    },
    {
      img: '../../images/emoji/mt.png',
      text: '[面条]'
    },
    {
      img: '../../images/emoji/xj.png',
      text: '[香蕉]'
    },
    {
      img: '../../images/emoji/fj.png',
      text: '[飞机]'
    },
    {
      img: '../../images/emoji/zct.png',
      text: '[左车头]'
    },
    {
      img: '../../images/emoji/cx.png',
      text: '[车厢]'
    },
    {
      img: '../../images/emoji/yct.png',
      text: '[右车头]'
    },
    {
      img: '../../images/emoji/dy1.png',
      text: '[多云]'
    },
    {
      img: '../../images/emoji/xy.png',
      text: '[下雨]'
    },
    {
      img: '../../images/emoji/cp.png',
      text: '[钞票]'
    },
    {
      img: '../../images/emoji/xm.png',
      text: '[熊猫]'
    },
    {
      img: '../../images/emoji/dp.png',
      text: '[灯泡]'
    },
    {
      img: '../../images/emoji/fc.png',
      text: '[风车]'
    },
    {
      img: '../../images/emoji/nz.png',
      text: '[闹钟]'
    },
    {
      img: '../../images/emoji/ys.png',
      text: '[雨伞]'
    },
    {
      img: '../../images/emoji/cq.png',
      text: '[彩球]'
    },
    {
      img: '../../images/emoji/zj.png',
      text: '[钻戒]'
    },
    {
      img: '../../images/emoji/sf.png',
      text: '[沙发]'
    },
    {
      img: '../../images/emoji/zj1.png',
      text: '[纸巾]'
    },
    {
      img: '../../images/emoji/sq.png',
      text: '[手枪]'
    },
    {
      img: '../../images/emoji/qw.png',
      text: '[青蛙]'
    },

    ],
    nextReqMessageID:''
  },
  toxq(e) {
    var type = e.currentTarget.dataset.type;
    var id = e.currentTarget.dataset.id;
    if(type == 0){
      setTimeout(function() {
        wx.navigateTo({
          url: '/pages/goods/page/goodsXiangqing/putongGoods/putongGoods?goodsid=' + id,
        })
      }, 150)
    }
    if(type == 1){
      setTimeout(function() {
        wx.navigateTo({
          url: '/pages/goods/page/goodsXiangqing/manjianGoods/manjianGoods?goodsid=' + id,
        })
      }, 150)
    }
    if(type == 2){
      setTimeout(function() {
        wx.navigateTo({
          url: '/pages/goods/page/goodsXiangqing/mansongGoods/mansongGoods?goodsid=' + id,
        })
      }, 150)
    }
    if(type == 3){
      setTimeout(function() {
        wx.navigateTo({
          url: '/pages/goods/page/goodsXiangqing/xianshiGoods/xianshiGoods?goodsid=' + id,
        })
      }, 150)
    }
    if(type == 4){
      setTimeout(function() {
        wx.navigateTo({
          url: '/pages/goods/page/goodsXiangqing/tuanpinGoods/tuanpinGoods?goodsid=' + id,
        })
      }, 150)
    }
    if(type == 5){
      setTimeout(function() {
        wx.navigateTo({
          url: '/pages/goods/page/goodsXiangqing/twopinGoods/twopinGoods?goodsid=' + id,
        })
      }, 150)
    }
  },
  //解析消息
  addMsg(msg) {
    var _this = this;
    if (msg.flow == 'out'){
      msg.headimg = wx.getStorageSync('userInfo').avatarUrl;
      msg.nickname = wx.getStorageSync('userInfo').nickName;
    }else{
      msg.nickname = _this.data.friendName;
      msg.headimg = _this.data.friendAvatarUrl;
    }
    var msgTime = msg.time;
    var timeStamp = new Date(new Date().setHours(0, 0, 0, 0)) / 1000;
    var thisdate;
    var d = new Date(msgTime * 1000); //根据时间戳生成的时间对象
    var min = d.getMinutes();
    var hour = d.getHours();
    //得到时和分，分小于10时，只返回一位数
    if (min < 10) {
      min = "0" + min;
    }
    //得到月份和天  月份一般是从0开始，所以展示出来要+1
    var month = d.getMonth();

    var day = d.getDate();
    //得到时间   当天时间应该只显示时分  当天以前显示日期+时间
    if (timeStamp > msgTime) {
      thisdate = month + 1 + "-" + day + " " + hour + ":" + min;
    } else {
      thisdate = hour + ":" + min;
    }
    msg.time = thisdate;
    if (msg.type == "TIMTextElem" ){
      let renderDom = [];
      let temp = msg.payload.text
      let left = -1
      let right = -1
      var bqlist = _this.data.bqlist;
      while (temp !== '') {
        left = temp.indexOf('[')
        right = temp.indexOf(']')
        switch (left) {
          case 0:
            if (right === -1) {
              renderDom.push({
                name: 'text',
                text: temp
              })
              temp = ''
            } else {
              let _emoji = temp.slice(0, right + 1)
              if (bqlist[_emoji]) {    // 如果您需要渲染表情包，需要进行匹配您对应[呲牙]的表情包地址
                renderDom.push({
                  name: 'img',
                  src: bqlist[_emoji]
                })
                temp = temp.substring(right + 1)
              } else {
                renderDom.push({
                  name: 'text',
                  text: '['
                })
                temp = temp.slice(1)
              }
            }
            break
          case -1:
            renderDom.push({
              name: 'text',
              text: temp
            })
            temp = ''
            break
          default:
            renderDom.push({
              name: 'text',
              text: temp.slice(0, left)
            })
            temp = temp.substring(left)
            break
        }
      }
      msg.payload.text = renderDom
    }
    if (msg.type == "TIMSoundElem" ){
      msg.payload.text = '收到一条语音消息，请前往app查看'
    }
    // if(msg.type == 'TIMCustomElem'){

    //   msg.payload.text = '收到条自定义消息'
    // }

    return msg;
  },
  getMorexiaoxi(){
    setTimeout(function () {
      wx.showLoading({
        title: '加载中',
      })
    }, 0)
    let that = this
    let conversationID = 'C2C' + that.data.selToID
    let nextReqMessageID = that.data.nextReqMessageID
    let promise = that.tim.getMessageList({ conversationID: conversationID, nextReqMessageID, count: 15 });
    promise.then(function (imResponse) {
      const messageList = imResponse.data.messageList; // 消息列表。
      const nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
      const isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
      for (let i in messageList) {
        var msgTime = messageList[i].time; //得到当前消息发送的时间
        if (messageList[i].to == that.data.selToID) {
          messageList[i].type = 0
          messageList[i].img = wx.getStorageSync('shopImg')
        } else {
          messageList[i].type = 1
          messageList[i].img = that.data.friendAvatarUrl
        }
        if (messageList[i].elements[0].type == 'TIMImageElem') {
          messageList[i].imgurl = messageList[i].elements[0].content.imageInfoArray[1].imageUrl
        } else if (messageList[i].elements[0].type == 'TIMTextElem') {
          var str = that.convertMsgtoHtml(messageList[i].elements)
          var listt = that.data.bqlist;
          var bqtype = false;
          var bqurl = '';
          var msglist = [];
          for (let j in str) {
            var qwe = false;
            for (let i in listt) {
              if (listt[i].text == str[j]) {
                qwe = true
                msglist.push({
                  bqtype: true,
                  bqurl: listt[i].img
                })
              }
            }
            if (qwe == false) {
              msglist.push({
                bqtype: false,
                text: str[j]
              })
            }
          }
          messageList[i].msglist = msglist
        }
        // //得到当天凌晨的时间戳
        var timeStamp = new Date(new Date().setHours(0, 0, 0, 0)) / 1000;
        var thisdate;
        var d = new Date(msgTime * 1000); //根据时间戳生成的时间对象
        var min = d.getMinutes();
        var hour = d.getHours();
        //得到时和分，分小于10时，只返回一位数
        console.log(min, hour)
        if (min < 10) {
          min = "0" + min;
        }
        //得到月份和天  月份一般是从0开始，所以展示出来要+1
        var month = d.getMonth();
        var day = d.getDate();
        //得到时间   当天时间应该只显示时分  当天以前显示日期+时间
        if (timeStamp > msgTime) {
          thisdate = month + 1 + "-" + day + " " + hour + ":" + min;
        } else {
          thisdate = hour + ":" + min;
        }
        messageList[i].nowtime = thisdate
      }
      let messageLists = messageList.concat(that.data.list)
      that.setData({
        list: messageLists,
        nextReqMessageID: nextReqMessageID
      })
      console.log(that.data.list)
    });
    setTimeout(function () {
      wx.hideLoading()
    }, 500)
  },
  bigimg(e) {
    var url = e.currentTarget.dataset.url;
    wx.previewImage({
      current: url, // 当前显示图片的http链接
      urls: [url] // 需要预览的图片http链接列表
    })
  },
  xuanimgpai() {
    var that = this;
    var msglist = this.data.list;
    wx.chooseImage({
      count: 1, //最多可以选择的图片总数
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['camera'],
      success: resss => {
        // console.log(resss)
        if (resss.tempFiles[0].size >= 1024 * 1024) {
          wx.showToast({
            title: '图片过大,请重新选择',
            icon: 'none',
            duration: 1000
          })
          return false;
        }
        setTimeout(function () {
          let message = that.tim.createImageMessage({
            to: that.data.selToID,
            conversationType: TIM.TYPES.CONV_C2C,
            payload: { file: resss },
            onProgress: function (event) { console.log('file uploading:', event) }
          });
          // 3. 发送图片
          let promise = that.tim.sendMessage(message);
          promise.then(function (imResponse) {
            // 发送成功
            console.log(imResponse);
            msglist.push(imResponse.data.message)
            
            that.setData({
              list:msglist,
              content: '',
              imgtype: true
            })
            that.getlishiother();
          }).catch(function (imError) {
            // 发送失败
            console.log(promise,'快快快')
            console.warn('sendMessage error:', imError);
          });
        }, 800)

      },
    })
  },
  xuanimg() {
    var that = this;
    var msglist = this.data.list;
    wx.chooseImage({
      count: 1, //最多可以选择的图片总数
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'],
      success: resss => {
        // console.log(resss)
        if (resss.tempFiles[0].size >= 1024 * 1024) {
          wx.showToast({
            title: '图片过大,请重新选择',
            icon: 'none',
            duration: 1000
          })
          return false;
        }
        setTimeout(function () {
        let message = that.tim.createImageMessage({
          to: that.data.selToID,
          conversationType: TIM.TYPES.CONV_C2C,
          payload: { file: resss },
          onProgress: function (event) { console.log('file uploading:', event) }
        });
        // 3. 发送图片
        let promise = that.tim.sendMessage(message);
        
        promise.then(function (imResponse) {
          // 发送成功

          console.log(imResponse);
          msglist.push(imResponse.data.message)
            
            that.setData({
              list:msglist,
              content: '',
              imgtype: true
            })
          that.getlishiother();
          that.setData({
            content: '',
            imgtype: true
          })
        }).catch(function (imError) {
          // 发送失败
          console.warn('sendMessage error:', imError);
        });
        }, 800)
      },
    })
  },
  //关闭框
  choose() {
    this.setData({
      bqtype: true,
      imgtype: true,
    })
  },
  tanbiaoqing() {
    var that = this;
    this.setData({
      bqtype: !that.data.bqtype,
      imgtype: true,
    })
  },
  tanimg() {
    var that = this;
    this.setData({
      bqtype: true,
      imgtype: !that.data.imgtype,
    })
  },
  //获取输入内容
  getContent: function (e) {
    var that = this;
    console.log(e.detail.value)
    if (e.detail.value) {
      var type = true
    } else {
      var type = false
    }
    if(e.detail.value){

    }
    console
    that.setData({
      content: e.detail.value,
      type: type
    })
  },

  //把消息转换成 HTML
  convertMsgtoHtml(msg) {
    var that = this;
    // console.log(msg, 5555555)
    var html = "",
      content;
    content = msg[0].content;
    // console.log(content)
    //解析文本和表情
    var expr = /\[[^[\]]{1,3}\]/mg;
    var emotions = content.text.match(expr);
    var arr = content.text.split(/\[[^[\]]{1,3}\]/)
    // console.log(arr)
    var arrindex = 0;
    for (let i in arr) {
      if (arr[i] == '') {
        arr[i] = emotions[arrindex];
        arrindex++
      }
    }
    // console.log(arr)
    if (!emotions || emotions.length < 1) {
      html += content.text;
    } else {
      html = arr;
    }
    return html;
  },
  //发送自定义消息
  // subshare(e){
  //   var _this = this
  //   var obj = JSON.stringify(_this.data.shareInfo);
  //   var selToID = this.data.selToID;
  //   var msglist = this.data.msglist;
  //   let message = tim.createCustomMessage({
  //     to: selToID,
  //     conversationType: TIM.TYPES.CONV_C2C,
  //     payload: {
  //       data: obj,
  //     }
  //   });
  //   // 2. 发送消息
  //   let promise = tim.sendMessage(message);
  //   promise.then(function(imResponse) {
  //     // 发送成功
  //     imResponse.data.message = _this.addMsg(imResponse.data.message)
      
  //       console.log(imResponse.data.message.payload.data)
  //       imResponse.data.message.payload.data = JSON.parse(imResponse.data.message.payload.data)
      
  //     msglist.push(imResponse.data.message)
  //     console.log(imResponse);
      
      
  //     _this.setData({
  //       msglist: msglist,
  //     })
      
  //     console.log(_this.data.msglist)

  //   }).catch(function(imError) {
  //     // 发送失败
  //     console.warn('sendMessage error:', imError);
  //   });
  // },
  subbq(e) {
    var content = e.currentTarget.dataset.text
    var that = this;
    var selSess = this.data.selSess;
    var selToID = this.data.selToID;
    var friendHeadUrl = this.data.friendAvatarUrl;
    if (content.length < 1) {
      wx.showToast({
        title: '发送的消息不能为空',
        duration: 1000,
        icon: 'none'
      })
      that.setData({
        content: '',
        type:false
        
      })
      return;
    }else{
      let contentarr = that.data.content
      that.setData({
        content: contentarr+content,
        type:true
      })
    }

  //   let message = that.tim.createTextMessage({
  //     to: selToID,
  //     conversationType: TIM.TYPES.CONV_C2C,
  //     payload: {
  //       text: content
  //     }
  //   });
  //  // 2. 发送消息
  //   let promise = that.tim.sendMessage(message);
  //   promise.then(function (imResponse) {
  //     // 发送成功
  //     // console.log(imResponse);
  //     that.setData({
  //       content: '',
  //       bqtype:true
  //     })
  //     that.getlishi()
  //   }).catch(function (imError) {
  //     // 发送失败
  //     console.warn('sendMessage error:', imError);
  //   });
  },
  onSendMsg() {
    var that = this;
    var selToID = that.data.selToID;
    var friendHeadUrl = that.data.friendAvatarUrl;
    var msglist = that.data.list;
    //获取消息内容
    var msgtosend = that.data.content;
    if (msgtosend.length < 1) {
      wx.showToast({
        title: '发送的消息不能为空',
        duration: 1000,
        icon: 'none'
      })
      that.setData({
        content: ''
      })
      return;
    }
    let message = that.tim.createTextMessage({
      to: selToID,
      conversationType: TIM.TYPES.CONV_C2C,
      payload: {
        text: msgtosend
      }
    });
    // 2. 发送消息
    let promise = that.tim.sendMessage(message);
    promise.then(function (imResponse) {
      // 发送成功
      console.log(imResponse.data.message);
      // imResponse.data.message = that.addMsg(imResponse.data.message)
      msglist.push(imResponse.data.message)
      that.setData({
        content: '',
        list:msglist
      })
      that.getlishiother()
    }).catch(function (imError) {
      // 发送失败
      console.warn('sendMessage error:', imError);
    });
  },
  //解析文本消息元素
  convertTextMsgToHtml(contentt) {
    return contentt.getText();
  },
  //解析表情消息元素
  convertFaceMsgToHtml(content) {
    var index = content.getIndex();
    var data = content.getData();
    var url = null;
    var emotion = webim.Emotions[index];
    if (emotion && emotion[1]) {
      url = emotion[1];
    }
    if (url) {
      return url;
    } else {
      return data;
    }
  },
  webimLogin() {
    var that = this;
    var options = {
      SDKAppID: 1400437598 // 接入时需要将0替换为您的即时通信应用的 SDKAppID
    };
    // 创建 SDK 实例，TIM.create() 方法对于同一个 SDKAppID 只会返回同一份实例
    var tim = TIM.create(options);
    this.tim = tim
    tim.registerPlugin({ 'cos-wx-sdk': COS });
    tim.setLogLevel(1);


    
    let promises = tim.login({
      userID: wx.getStorageSync('userId'),
      userSig: wx.getStorageSync('userSig')
      // userID: '5067538ef91b4bbd8aefd0db908a21a2',
      // userSig: 'eJxFkEtPg0AUhf8La2Mv8yiMu5ZiitAFtiS6IjPMDJ0oD2HAVuN-FwmN2-Pdk5Pvfjun5HjP29bInNscd9J5cMC5m2N1aU2ncq6t6qbYpZQigBsdVdebpp4AApe6CAP8QyNVbY02c5HC2qPYV5q5ggghfa60BCkY*By5HC2d3pTT8SF8DaI0*Aga3F6Pp-Nh7GUjNlnq6ZfHeOBfpAqfA40EG*0Ks0Sl0XkTFeSTJ1m6rUhWDfEI7xfBi-Gp2tFyb6Jem32ocBSXu*w2Jt-yWftPjAAgoIyRBVpTqVnYA*p7HlkvOS*KZqhtbq*tmv-08wvhoV*d'
    });
    promises.then(function (imResponse) {
      console.log(imResponse.data, '登录成功'); // 登录成功
      setTimeout(function () {
        that.getlishi();
      }, 800)
      
      // that.getxiaoxi()
    }).catch(function (imError) {
      console.warn('login error:', imError); // 登录失败的相关信息
    });
    setTimeout(function () {
      tim.on(TIM.EVENT.MESSAGE_RECEIVED, function (event) {
        console.log(event.data, '收到推送的私聊、群聊、群提示、群系统通知的新消息')
        if (event.data[0].from == that.data.friendId) {
          var messageList = that.data.list;
          // event.data[0] = that.addMsg(event.data[0]);
          messageList.push(event.data[0])
          for (let i in messageList) {
        var msgTime = messageList[i].time; //得到当前消息发送的时间
        
       

        if (messageList[i].to == that.data.selToID) {
          
          messageList[i].img = wx.getStorageSync('shopImg')
        } else {
          messageList[i].img = that.data.friendAvatarUrl
        }

        if (messageList[i].elements[0].type == 'TIMImageElem') {
          messageList[i].imgurl = messageList[i].elements[0].content.imageInfoArray[1].imageUrl
        } else if (messageList[i].elements[0].type == 'TIMTextElem') {
          var str = that.convertMsgtoHtml(messageList[i].elements)
          var listt = that.data.bqlist;
          var bqtype = false;
          var bqurl = '';
          var msglist = [];
          for (let j in str) {
            var qwe = false;
            for (let i in listt) {
              if (listt[i].text == str[j]) {
                qwe = true
                msglist.push({
                  bqtype: true,
                  bqurl: listt[i].img
                })
              }
            }
            if (qwe == false) {
              msglist.push({
                bqtype: false,
                text: str[j]
              })
            }
          }
          messageList[i].msglist = msglist
        }
        
        // //得到当天凌晨的时间戳
        var timeStamp = new Date(new Date().setHours(0, 0, 0, 0)) / 1000;
        var thisdate;
        var d = new Date(msgTime * 1000); //根据时间戳生成的时间对象
        var min = d.getMinutes();
        var hour = d.getHours();
        //得到时和分，分小于10时，只返回一位数
        // console.log(min, hour)
        if (min < 10) {
          min = "0" + min;
        }
        //得到月份和天  月份一般是从0开始，所以展示出来要+1
        var month = d.getMonth();
        var day = d.getDate();
        //得到时间   当天时间应该只显示时分  当天以前显示日期+时间
        if (timeStamp > msgTime) {
          thisdate = month + 1 + "-" + day + " " + hour + ":" + min;
        } else {
          thisdate = hour + ":" + min;
        }
        messageList[i].nowtime = thisdate
      }
      // console.log(messageList)
      that.setData({
        list: messageList
      })
  
         
          setTimeout(function () {
            that.tobottom();
            that.getlishi();
          }, 500)
        }
        // 收到推送的私聊、群聊、群提示、群系统通知的新消息，可通过遍历 event.data 获取消息列表数据并渲染到页面
        // event.name - TIM.EVENT.MESSAGE_RECEIVED
        // event.data - 存储 Message 对象的数组 - [Message]
      });
    }, 400)

  },
  // getxiaoxi(){
  //   tim.on(TIM.EVENT.MESSAGE_RECEIVED, function (event) {
  //     console.log(event.data, '收到推送的私聊、群聊、群提示、群系统通知的新消息')
  //     that.getlishi();
  //     // 收到推送的私聊、群聊、群提示、群系统通知的新消息，可通过遍历 event.data 获取消息列表数据并渲染到页面
  //     // event.name - TIM.EVENT.MESSAGE_RECEIVED
  //     // event.data - 存储 Message 对象的数组 - [Message]
  //   });
  // },
  getlishiother(){
    var that = this;
    // 打开某个会话时，第一次拉取消息列表
    let promise = that.tim.getMessageList({
      conversationID: 'C2C' + that.data.selToID,
      count: 15
    });
    promise.then(function (imResponse) {
      const messageList = imResponse.data.messageList; // 消息列表。
     

      const nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
      const isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
      console.log(messageList, nextReqMessageID, isCompleted)
      that.setData({
        nextReqMessageID: nextReqMessageID
      })
      for (let i in messageList) {
        var msgTime = messageList[i].time; //得到当前消息发送的时间
        //是否有自定义消息
        // if(messageList[i].type == 'TIMCustomElem'){
        //   messageList[i].payload.data = JSON.parse( messageList[i].payload.data);
        //   // messageList[i].imgurl = messageList[i].elements[0].content.imageInfoArray[1].imageUrl
        // }
       

        if (messageList[i].to == that.data.selToID) {
          
          messageList[i].img = wx.getStorageSync('shopImg')
        } else {
          messageList[i].img = that.data.friendAvatarUrl
        }

        if (messageList[i].elements[0].type == 'TIMImageElem') {
          messageList[i].imgurl = messageList[i].elements[0].content.imageInfoArray[1].imageUrl
        } else if (messageList[i].elements[0].type == 'TIMTextElem') {
          var str = that.convertMsgtoHtml(messageList[i].elements)
          var listt = that.data.bqlist;
          var bqtype = false;
          var bqurl = '';
          var msglist = [];
          for (let j in str) {
            var qwe = false;
            for (let i in listt) {
              if (listt[i].text == str[j]) {
                qwe = true
                msglist.push({
                  bqtype: true,
                  bqurl: listt[i].img
                })
              }
            }
            if (qwe == false) {
              msglist.push({
                bqtype: false,
                text: str[j]
              })
            }
          }
          messageList[i].msglist = msglist
        }
        
        // //得到当天凌晨的时间戳
        var timeStamp = new Date(new Date().setHours(0, 0, 0, 0)) / 1000;
        var thisdate;
        var d = new Date(msgTime * 1000); //根据时间戳生成的时间对象
        var min = d.getMinutes();
        var hour = d.getHours();
        //得到时和分，分小于10时，只返回一位数
        // console.log(min, hour)
        if (min < 10) {
          min = "0" + min;
        }
        //得到月份和天  月份一般是从0开始，所以展示出来要+1
        var month = d.getMonth();
        var day = d.getDate();
        //得到时间   当天时间应该只显示时分  当天以前显示日期+时间
        if (timeStamp > msgTime) {
          thisdate = month + 1 + "-" + day + " " + hour + ":" + min;
        } else {
          thisdate = hour + ":" + min;
        }
        messageList[i].nowtime = thisdate
      }
      // console.log(messageList)
      that.setData({
        list: messageList
      })
    });
    console.log()
    setTimeout(function () {
      that.tobottom();
    }, 500)
    setTimeout(function () {
      wx.hideLoading()
    }, 0)
  },
  getlishi() {
    var that = this;
    // 打开某个会话时，第一次拉取消息列表
    let promise = that.tim.getMessageList({
      conversationID: 'C2C' + that.data.selToID,
      count: 15
    });
    promise.then(function (imResponse) {
      const messageList = imResponse.data.messageList; // 消息列表。
     

      const nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
      const isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
      console.log(messageList, nextReqMessageID, isCompleted)
      that.setData({
        nextReqMessageID: nextReqMessageID
      })
      for (let i in messageList) {
        var msgTime = messageList[i].time; //得到当前消息发送的时间
        //是否有自定义消息
        if(messageList[i].type == 'TIMCustomElem'){
          messageList[i].payload.data = JSON.parse( messageList[i].payload.data);
          // messageList[i].imgurl = messageList[i].elements[0].content.imageInfoArray[1].imageUrl
        }
       

        if (messageList[i].to == that.data.selToID) {
          
          messageList[i].img = wx.getStorageSync('shopImg')
        } else {
          messageList[i].img = that.data.friendAvatarUrl
        }

        if (messageList[i].elements[0].type == 'TIMImageElem') {
          messageList[i].imgurl = messageList[i].elements[0].content.imageInfoArray[1].imageUrl
        } else if (messageList[i].elements[0].type == 'TIMTextElem') {
          var str = that.convertMsgtoHtml(messageList[i].elements)
          var listt = that.data.bqlist;
          var bqtype = false;
          var bqurl = '';
          var msglist = [];
          for (let j in str) {
            var qwe = false;
            for (let i in listt) {
              if (listt[i].text == str[j]) {
                qwe = true
                msglist.push({
                  bqtype: true,
                  bqurl: listt[i].img
                })
              }
            }
            if (qwe == false) {
              msglist.push({
                bqtype: false,
                text: str[j]
              })
            }
          }
          messageList[i].msglist = msglist
        }
        
        // //得到当天凌晨的时间戳
        var timeStamp = new Date(new Date().setHours(0, 0, 0, 0)) / 1000;
        var thisdate;
        var d = new Date(msgTime * 1000); //根据时间戳生成的时间对象
        var min = d.getMinutes();
        var hour = d.getHours();
        //得到时和分，分小于10时，只返回一位数
        // console.log(min, hour)
        if (min < 10) {
          min = "0" + min;
        }
        //得到月份和天  月份一般是从0开始，所以展示出来要+1
        var month = d.getMonth();
        var day = d.getDate();
        //得到时间   当天时间应该只显示时分  当天以前显示日期+时间
        if (timeStamp > msgTime) {
          thisdate = month + 1 + "-" + day + " " + hour + ":" + min;
        } else {
          thisdate = hour + ":" + min;
        }
        messageList[i].nowtime = thisdate
      }
      console.log(that.data.friendAvatarUrl)
      console.log(messageList)
      that.setData({
        list: messageList
      })
    });

    setTimeout(function () {
      that.tobottom();
    }, 500)
    setTimeout(function () {
      wx.hideLoading()
    }, 0)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    var that = this;
    setTimeout(function () {
      wx.showLoading({
        title: '加载中',
      }) 
    }, 0)
   
    if (options) { // 设置会话列表传参过来的好友id
      that.setData({
        selToID: options.friendId,
        friendId: options.friendId,
        friendName: options.friendName,
        friendAvatarUrl: options.friendAvatarUrl
      })
      wx.setNavigationBarTitle({
        title: options.friendName
      })
      // wx.showLoading({
      //   title: '加载中',
      // })
      setTimeout(function(){
        that.getlishi();
      },1000)
    }


  },
  pageScrollToBottom: function () {
    var that = this;
    var height = wx.getSystemInfoSync().windowHeight;
    var width = wx.getSystemInfoSync().windowWidth;
    var height = height / ((width * 2) / 750);
    // console.log(height)
    wx.createSelectorQuery().select('#page').boundingClientRect(function (rect) {
      if (rect) {
        // console.log(rect)
        that.setData({
          windowHeight: height,
          // scrollTop:  rect.height,
        })

      }
    }).exec()
  },
  tobottom() {
    this.setData({
      id: 'bottom'
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var that = this;
    var height = wx.getSystemInfoSync().windowHeight;
    var width = wx.getSystemInfoSync().windowWidth;
    var height = height / ((width * 2) / 750);
    wx.createSelectorQuery().select('#page').boundingClientRect(function (rect) {
      if (rect) {
        // console.log(rect)
        that.setData({
          windowHeight: height,
          // scrollTop:  rect.height,
        })
      }
    }).exec()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    that.webimLogin()
    var list = this.data.bqlist;
    var length = Math.ceil(list.length / 21)
    // console.log(length)
    this.setData({
      length: length
    })
    setTimeout(function () {
      that.tobottom();
    }, 500)




  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})